package com.zmzncs.lmtc.common.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;

@Slf4j
@Configuration
public class MdcThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void execute(Runnable runnable) {
        Map<String, String> context = MDC.getCopyOfContextMap();
        super.execute(() -> run(runnable, context));
    }

    /**
     * 子线程委托的执行方法
     *
     * @param runnable {@link Runnable}
     * @param context 父线程MDC内容
     */
    private void run(Runnable runnable, Map<String, String> context) {
        // 将父线程的MDC内容传给子线程
        MDC.setContextMap(context);
        try {
            // 执行异步操作
            runnable.run();
        } finally {
            try {
                MDC.clear();
            } catch (Exception e2) {
                log.error("清除mdc异常", e2);
            }
        }
    }
}